package top.oneit.jdownload.stages;

import cn.hutool.core.lang.Assert;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.WindowEvent;
import top.oneit.jdownload.constants.JConstants;
import top.oneit.jdownload.controller.item.ActionsItemController;
import top.oneit.jdownload.data.dao.DownloadingTablePoDao;
import top.oneit.jdownload.data.entity.DownloadingTablePo;
import top.oneit.jdownload.utils.StorageUtils;
import top.oneit.jdownload.utils.XmlUtils;

import java.io.IOException;
import java.util.List;

public class HomeStage extends BaseStage {
    // 创建一个正在下载的表格
    public ObservableList<DownloadingTablePo> downloadingTablePos = FXCollections.observableArrayList();

    private AnchorPane root;

    public HomeStage() {
        // 首次启动软件，所有下载任务设置为暂停状态
        DownloadingTablePoDao.initDownloadingToPause();
        refreshTable();
        setXML("/fxml/main.fxml");
        getIcons().add(new Image("assets/茶壶.png"));
        setTitle("JDownload");
        show();
        // X 掉窗口就退出
        setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                System.exit(0);
            }
        });
    }

    public void refreshTable() {
        List<DownloadingTablePo> list = DownloadingTablePoDao.getNotFinish();
        downloadingTablePos.clear();
        for (DownloadingTablePo e : list) {
            if (JConstants.FILE_STATUS_FINISH.equals(e.getStatus())) {
                downloadingTablePos.remove(e);
                continue;
            }
            boolean exist = false;
            for (DownloadingTablePo po : downloadingTablePos) {
                if (po.getId().equals(e.getId())) {
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                FXMLLoader actionsLoader = XmlUtils.getFXMLLoader("/fxml/item/actions-item.fxml");
                e.setSizeStr(StorageUtils.byteToString(e.getSize()));
                Integer alreadyDownloadSize = DownloadingTablePoDao.getAlreadyDownloadSize(e);
                e.setSurplus(e.getSize() - alreadyDownloadSize);
                e.setSurplusStr(new Label(StorageUtils.byteToString(e.getSize() - alreadyDownloadSize)));
                e.setSpeed(new Label("0 kb/s"));
                actionsLoader.setController(new ActionsItemController(e));
                try {
                    Object load = actionsLoader.load();
                    e.setActions((HBox) load);
                } catch (IOException ioException) {
                    Assert.isNull(ioException, "加载列表失败！");
                }
                downloadingTablePos.add(e);
            }
        }
    }
}
